import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:kasax/commons/commons.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax_demos2/providers/data_providers.dart';

/// 基于http: ^0.13.3
/// https://pub.dev/packages/http/versions/0.13.3/example
/// https://reqbin.com/ 在线请求测试
class HttpDemo2 extends StatefulWidget {
  const HttpDemo2({Key? key}) : super(key: key);

  @override
  _HttpDemo2State createState() => _HttpDemo2State();
}

class _HttpDemo2State extends State<HttpDemo2> {
  List<Posts> posts = <Posts>[];

  @override
  void initState() {
    super.initState();
    // testJson();
    DataProvider.getInstance().fetchAllPosts().then((value) {
      log("list.len: ${value.length}");
      setState(() {
        posts.addAll(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: buildContent());
  }

  buildContent() {
    return posts.isEmpty ? buildLoadingWidget() : buildListView2();
  }

  ListView buildListView2() {
    return ListView(
      children: posts
          .map<Widget>((e) => Padding(
                padding: EdgeInsets.only(top: 15),
                child: ListTile(
                  title: Text(e.title),
                  subtitle: Text(
                    e.description,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 3,
                  ),
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(e.imageUrl),
                  ),
                ),
              ))
          .toList(),
    );
  }

  ListView buildListView() {
    return ListView.separated(
      itemCount: posts.length,
      itemBuilder: (context, index) {
        final post = posts[index];
        return ListTile(
          title: Text(post.title),
          subtitle: Text(post.description),
          leading: CircleAvatar(
            backgroundImage: NetworkImage(post.imageUrl),
          ),
        );
      },
      separatorBuilder: (context, index) => Divider(),
    );
  }
}
